export default {
    install(Vue, options) {
        // 常量定义
        Vue.prototype.empty_data = '请点击搜索查看';
        Vue.prototype.pageInfo = {totalPages : 0, pageSize : 20, totalElements : 0, currentPage : 1, queryParams : {}};
        Vue.prototype.global_config = {
            request_prefix: process.env.REST_API_URL,
            _lock_pool: new Array(),
            _g_lock: false,
            _loading_container: null
        };
        //全局过滤器
        Vue.filter("yuan",function(val, len){
            //格式化成元
            if(isNaN(val)){
                return val;
            }
            return Number(val * 0.01).toFixed(len ? len : 2);
        });
        Vue.filter("formatDate",function(val, fmt){
            if(val == null || val === ''){
                return val;
            }
            var date = new Date(val);
            if(date == null){
                return val;
            }
            return dateFormat(date, fmt ? fmt : 'yyyy-MM-dd hh:mm:ss');
        });
        Array.prototype.indexOf = function (obj) {
            let i = this.length;
            while (i--) {
                if (this[i] === obj) {
                    return i;
                }
            }
            return -1;
        };
        Vue.prototype.$lockButton = function (btnId) {
            let self = this;
            if (btnId) {
                let i = self.global_config._lock_pool.indexOf(btnId);
                if (i === -1) {
                    self.global_config._lock_pool.push(btnId);
                }
            } else {
                self.global_config._g_lock = true;
            }
        };
        Vue.prototype.$unlockButton = function (btnId) {
            let self = this;
            if (btnId) {
                let i = self.global_config._lock_pool.indexOf(btnId);
                if (i !== -1) {
                    self.global_config._lock_pool.splice(i, 1);
                }
            } else {
                self.global_config._g_lock = false;
            }
        };
        Vue.prototype.$isLockedButton = function (btnId) {
            let self = this;
            if (btnId) {
                let i = self.global_config._lock_pool.indexOf(btnId);
                if (i !== -1) {
                    return true;
                }
                return false;
            } else {
                return self.global_config._g_lock;
            }
        };

        Vue.prototype.$ajax = function (_param) {
            let self = this;
            let param = _param && typeof(_param) === 'object' ? _param : {};
            let settings = {
                type: param.type ? param.type : 'POST',
                url: self.global_config.request_prefix + param.url,
                data: param.data ? param.data : {},
                crossDomain: true,
                xhrFields: { withCredentials: true },
                dataType: param.dataType ? param.dataType : 'JSON'
            };
            if(param.contentType){
                settings.contentType = param.contentType;
            }
            settings.success = function (respData) {
                if (respData && typeof(respData) === 'object') {
                    // 1.未认证
                    if (respData.code === 401) {
                          self.$goRoute('/unauthorized');
                          return;
                    }
                    // 2.未授权
                    if (respData.code === 4013) {
                          self.$goRoute('/forbidden');
                          return;
                    }
                }
                if (param.success && typeof(param.success) === 'function') {
                    param.success(respData);
                }
            };
            settings.error = function(xmlHttpRequest, textStatus, errorThrown) {
                if (param.error && typeof(param.error) === 'function') {
                    param.error(xmlHttpRequest, textStatus, errorThrown);
                } else {
                    self.$message({
                      showClose: true,
                      message: '请求出现异常，请与管理员联系！',
                      type: 'error',
                      duration:3000
                    });
                }
            };
            jQuery.ajax(settings);
        };
        Vue.prototype.$doPost = function (_url, _params, _callback, _errorCallback) {
            this.$ajax({type:'POST', url:_url, data:_params, success:_callback, error:_errorCallback});
        };
        Vue.prototype.$doGet = function (_url, _params, _callback, _errorCallback) {
            this.$ajax({type:'GET', url:_url, data:_params, success:_callback, error:_errorCallback});
        };

        // 缓存本地变量
        Vue.prototype.$saveStorage = function (_key, _value) {
            _key = 'lxb_admin_' + _key;
            sessionStorage.setItem(_key, _value);
        };
        Vue.prototype.$getStorage = function (_key) {
            _key = 'lxb_admin_' + _key;
            return sessionStorage.getItem(_key);
        };

        // 跳转默认首页
        Vue.prototype.$goDefaultPage = function () {
            this.$openTabPage({path: '/default', title: '首页管理'});
        };

        // 通过标签页打开
        Vue.prototype.$openTabPage = function (menuItem) {
            let flag = false;
            let tabOptions = this.$store.state.options;
            for (let option of tabOptions ) {
                if (option.path === menuItem.path) {
                    flag = true;
                    this.$store.commit('set_active_index', option.path);
                    break;
                }
            }
            if (!flag) {
                this.$store.commit('add_tabs', menuItem);
            }
            this.$goRoute(menuItem.path);
        };

        // 清除多标签页缓存
        Vue.prototype.$clearSessionCache = function () {
            sessionStorage.clear();
            this.$store.commit('clear_datas');
        };
        // 获取当前页面操作权限
        Vue.prototype.$getPageRights = function (path) {
            let vpath = path;
            if (! path) {
                vpath = this.$route.path;
            }
            if (this.$store.state.tabRights[vpath] === undefined) {
                var cacheTabItem = sessionStorage.getItem('lxb_tab_active_item');
                if (cacheTabItem) {
                    cacheTabItem = JSON.parse(cacheTabItem);
                    this.$store.commit('set_tab_rights', cacheTabItem);
                } else {
                    this.$store.commit('set_tab_rights', {path: vpath, opsRights: []});
                }
            }
            return this.$store.state.tabRights[vpath];
        };
        Vue.prototype.$loadShow = function(msg,target){
            var self = this;
            self.global_config._loading_container = self.$loading({
                target: target ? target : null,
                lock: true,
                text: msg ? msg : '加载中',
                customClass:'load-bg'
            });
        };
        Vue.prototype.$loadHide = function(){
            if(this.global_config._loading_container != null){
                this.global_config._loading_container.close();
            }
        };
        //权限验证
        Vue.prototype.$auth = function (permissions){
            if(permissions == null || $.trim(permissions) === ''){
                return false;
            }
            var permissionsList = this.$getStorage('permissions');
            if(permissionsList == null){
                return false;
            }
            var arr = permissionsList.split(',');
            for (var i = arr.length - 1; i >= 0; i--) {
                if(permissions === arr[i]){
                    return true;
                }
            }
            return false;
        };
    }
};
function dateFormat(date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
        }
    }
    return fmt;
};
